package com.dalianpai.gulimall.order.config;

import com.dalianpai.gulimall.order.entity.OrderEntity;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author WGR
 * @create 2020/8/6 -- 14:46
 */
@Configuration
public class MyMQConfig {

//    @SneakyThrows
//    @RabbitListener(queues = "order.release.order.queue")
//    public void listener(OrderEntity entity, Channel channel,Message message){
//        System.out.println("收到消息"+entity.getOrderSn());
//        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//    }

    //声明队列
    @Bean("orderDelayQueue")
    public Queue orderDelayQueue(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange","order-event-exchange");
        arguments.put("x-dead-letter-routing-key","order.release.order");
        arguments.put("x-message-ttl",60000);

        //谷粒视频中是new出来的，这个相当于封装了一下，用起来更方便
        return QueueBuilder.durable("order.delay.queue").withArguments(arguments).build();
    }

    @Bean("orderReleaseOrderQueue")
    public Queue orderReleaseOrderQueue(){
        return QueueBuilder.durable("order.release.order.queue").build();
    }

    @Bean("orderEventExchange")
    public Exchange orderEventExchange(){
        return ExchangeBuilder.topicExchange("order-event-exchange").durable(true).build();
    }

    //绑定队列和交换机
    @Bean
    public Binding bingOrderDelayQueue(@Qualifier("orderDelayQueue") Queue queue,
                                     @Qualifier("orderEventExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange)
                .with("order.create.order").noargs();
    }

    //绑定队列和交换机
    @Bean
    public Binding bingOrderReleaseOrderQueue(@Qualifier("orderReleaseOrderQueue") Queue queue,
                                              @Qualifier("orderEventExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange)
                .with("order.release.order").noargs();
    }

    //绑定队列和交换机
    @Bean
    public Binding bingOrderReleaseOtherBinding(){
        return new Binding("stock.release.stock.queue",Binding.DestinationType.QUEUE,
                "order-event-exchange","order.release.other.#",null);
    }

    @Bean
    public Queue orderSecKillQueue(){
        return new Queue("order.seckill.order.queue", true, false, false);
    }

    @Bean
    public Binding orderSecKillQueueBinding(){
        return new Binding("order.seckill.order.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.seckill.order", null);
    }
}
